<template>
  <div ref="chartContainer" class="trading-chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  chartData: {
    type: Array,
    required: true,
    default: () => []
    // 数据格式: [{ Date: '2023-01-01', BuyVol: 1000, SellVol: 500, Price: 10.5 }, ...]
  },
  height: {
    type: String,
    default: '400px'
  }
})

// 图表容器引用
const chartContainer = ref(null)
let chartInstance = null

// 处理数据
const processData = () => {
  if (!props.chartData || props.chartData.length === 0) {
    return {
      dates: [],
      prices: [],
      buyPoints: [],
      sellPoints: []
    }
  }

  const dates = []
  const prices = []
  const buyPoints = []
  const sellPoints = []

  props.chartData.forEach((item, index) => {
    dates.push(item.date)
    prices.push(item.price)

    // 根据BuyVol字段添加买入点
    if (item.buyVol && item.buyVol > 0) {
      buyPoints.push({
        name: item.date,
        value: [index, item.price],
        symbolSize: Math.max(8, Math.min(20, item.buyVol / 1000)), // 根据买入量调整点的大小
        vol: item.buyVol,
        isBuy: true
      })
    }

    // 根据SellVol字段添加卖出点
    if (item.sellVol && item.sellVol > 0) {
      sellPoints.push({
        name: item.date,
        value: [index, item.price],
        symbolSize: Math.max(8, Math.min(20, item.sellVol / 1000)), // 根据卖出量调整点的大小
        vol: item.sellVol,
        isBuy: false
      })
    }
  })

  return { dates, prices, buyPoints, sellPoints }
}

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return

  const { dates, prices, buyPoints, sellPoints } = processData()
  
  if (dates.length === 0) return

  chartInstance = echarts.init(chartContainer.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        let result = `${params[0].name}<br/>`
        
        params.forEach(param => {
          if (param.seriesName === '价格') {
            result += `价格: ${param.value[1].toFixed(2)}元<br/>`
          } else if (param.seriesName === '买入点') {
            result += `<span style="color: #67C23A">买入: ${param.data.vol.toLocaleString()} 股</span><br/>`
          } else if (param.seriesName === '卖出点') {
            result += `<span style="color: #F56C6C">卖出: ${param.data.vol.toLocaleString()} 股</span><br/>`
          }
        })
        
        return result
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#E0E0E0'
        }
      },
      axisLabel: {
        show: false,
        color: '#909399',
        fontSize: 12,
        formatter: function(value) {
          // 简化日期显示，例如 2023-01-01 -> 01-01
          return value.length > 5 ? value.substring(5) : value
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#EBEEF5'
        }
      },
      axisLabel: {
        show: false,
        color: '#909399',
        fontSize: 12,
        formatter: function(value) {
          return value.toFixed(2)
        }
      }
    },
    series: [
      {
        name: '价格',
        type: 'line',
        data: prices.map((price, index) => [index, price]),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 2,
          color: '#409EFF'
        }
      },
      {
        name: '买入点',
        type: 'scatter',
        data: buyPoints,
        symbol: 'triangle',
        symbolRotate: 0, // 向上的三角形表示买入
        itemStyle: {
          color: '#67C23A',
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          scale: true,
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        z: 10
      },
      {
        name: '卖出点',
        type: 'scatter',
        data: sellPoints,
        symbol: 'triangle',
        symbolRotate: 180, // 向下的三角形表示卖出
        itemStyle: {
          color: '#F56C6C',
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          scale: true,
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        z: 10
      }
    ]
  }

  chartInstance.setOption(option)
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) {
    initChart()
    return
  }

  const { dates, prices, buyPoints, sellPoints } = processData()
  
  chartInstance.setOption({
    xAxis: {
      data: dates
    },
    series: [
      {
        name: '价格',
        data: prices.map((price, index) => [index, price]),
        smooth: props.smooth,
        areaStyle: props.showArea ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: `${props.lineColor}4D` },
              { offset: 1, color: `${props.lineColor}1A` }
            ]
          }
        } : undefined
      },
      {
        name: '买入点',
        data: buyPoints
      },
      {
        name: '卖出点',
        data: sellPoints
      }
    ]
  })
}

// 监听图表数据变化
watch(() => props.chartData, () => {
  updateChart()
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  }, 100)
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.trading-chart-container {
  width: 100%;
  height: v-bind(height);
  border-radius: 4px;
}
</style>